import json, hashlib
from books import show_books, add_books, saue_book, has_book, sell_book, search_book
book_list = []

class User(object):
    def __init__(self, name,password, hash=True):
        self.name = name
        if hash:
            md5 = hashlib.md5()
            md5.update(password.encode("utf-8"))
            self.password = md5.hexdigest()
        else:
            self.password = password


    # 注册
    def register(self):
        # print(self.name, self.password)
        all_users = User.get_all_users()
        all_users.append(self)
        # print(self)
        with open("user.txt", 'w', encoding="utf-8") as f:
            all_users_dict = []
            for user in all_users:
                all_users_dict.append(user.__dict__)
            json.dump(all_users_dict, f)

    # 获取所有用户
    @classmethod
    def get_all_users(cls):
        all_users = []
        with open("user.txt", "r", encoding="utf-8") as f:
            s = f.read()
            if s:
                json_obj = json.loads(s, encoding="utf-8")
                for user_dict in json_obj:
                    user = dict2user(user_dict)
                    all_users.append(user)
        return all_users

    @classmethod
    def has_user(cls, name):
        all_users = User.get_all_users()
        name_list = [user.name for user in all_users]
        if name in name_list:
            index = name_list.index(name)
            # print(all_users[index].name, all_users[index].password)
            # 返回用户
            return all_users[index]
        else:
            return None

    @classmethod
    def modify_pwd(self, name, pwd):
    	all_users = User.get_all_users()
    	name_list = [user.name for user in all_users]
    	r = name_list.index(name)
    	all_users[r].password = hashlib.md5(pwd.encode("utf-8")).hexdigest()
    	with open("user.txt", 'w', encoding="utf-8") as f:
            all_users_dict = []
            for user in all_users:
                all_users_dict.append(user.__dict__)
            json.dump(all_users_dict, f)




def dict2user(d_u):
	# print(d_u, "=======")
	return User(d_u['name'], d_u["password"], False)


# 登录，注册
while True:
	print("\t\t======欢迎进入图书管理系统======")
	cmd = input("请输入指令：1. 管理员登录 2. 成为管理员 3. 修改密码")
	if cmd == "2":
		name = input("请输入用户名:")
		all_users = User.get_all_users()
		if User.has_user(name) is None:
			password = input('请输入密码:')
			user = User(name,password)
			user.register()
			print("注册成功")
		else:
			print("用户名已经存在")
	elif cmd == "1":
	        name = input("请输入用户名:")
	        user = User.has_user(name)
	        if user is None:
	            print("用户名不存在!")
	        else:
	            pwd = input("请输入密码:")
	            md5 = hashlib.md5()
	            md5.update(pwd.encode("utf-8"))
	            # print(user.password, "======")
	            if user.password == md5.hexdigest():
	                print("登录成功!请选择您要管理的选项：")
	                while True:
	                	print("\t管理选项：")
		                print("\t添加图书：按1\n\t删除图书：按2\n\t搜索图书：按3\n\t展示图书：按4\n\t退出管理：按5")
		                cmd = input("\t请选择您要管理的选项\n")
		                if cmd == "1":
		                	add_books(book_list)
		                	print("添加成功！")
		                elif cmd == "2":
		                	sell_book(book_list)
		                elif cmd == "3":
		                	search_book(book_list)
		                elif cmd == "4":
		                	show_books(book_list)
		                elif cmd == "5":
		                	print("===感谢支持===")
		                	break
		                else:
		                	print("===指令无法接受===")
	            else:
	                print("密码错误")
	elif cmd == "3":
			all_users = User.get_all_users()
			name = input("请输入用户名：")
			r = User.has_user(name)
			if r is None:
				print("输入用户不存在")
			else:
				pwd = input("请输入密码：")
				User.modify_pwd(name, pwd)
				print("密码修改成功")


